public member function
<memory>

std::shared_ptr::operator bool

explicit operator bool() const noexcept;
Check if not null
Returns whether the stored pointer is a null pointer.

The stored pointer points to the object the shared_ptr object dereferences to, which is generally the same as its owned pointer (the pointer deleted when destroyed). They may be different if the shared_ptr object is an alias (i.e., alias-constructed objects and their copies).

The function returns the same as get()!=0.

Notice that a null shared_ptr (i.e., a pointer for which this function returns false) is not necessarily an empty shared_ptr. An alias may own some pointer but point to null, or an owner group may even own null pointers (see constructors 4 and 5).

Parameters

none

Return value

false if the shared_ptr is a null pointer.
true, otherwise.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// example of shared_ptr::operator bool
#include <iostream>
#include <memory>

int main () {
  std::shared_ptr<int> foo;
  std::shared_ptr<int> bar (new int(34));

  if (foo) std::cout << "foo points to " << *foo << '\n';
  else std::cout << "foo is null\n";

  if (bar) std::cout << "bar points to " << *bar << '\n';
  else std::cout << "bar is null\n";

  return 0;
}


Output:
foo is null
bar points to 34

See also